<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">基本资料</div>
    <el-form ref="userRef" label-width="80px" style="width: 500px" :rules="userRules">
      <el-form-item label="登录名称">
        <el-input v-model="user.username" disabled></el-input>
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickname">
        <el-input v-model="user.nickname"></el-input>
      </el-form-item>
      <el-form-item label="用户邮箱" prop="email">
        <el-input v-model="user.email"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="updateuserInfo">提交修改</el-button>
        <el-button>重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { updateUserAPI } from '@/api/user.js'
export default {
  name: 'Userinfo',
  methods: {
    updateUserInfo() {
      // 对表单数据进行校验
      // 校验通过之后发起ajax请求
      // 封装ajax接口并调用
      this.$refs.userRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await updateUserAPI(this.user)
        if (res.code !== 0) return this.$message.error('失败')
        this.$message.success('成功')
        this.$store.dispatch('initUser')
      })
    }
  },
  data() {
    return {
      // 通过浅拷贝，把vuex中的数据，拷贝一份形成一个新对象，页面的表单绑定到的数据源和vuex中的数据就无关了
      user: Object.assign({}, this.$store.state.user),
      userRules: {
        nickname: [
          { required: true, message: '用户昵称是必填项', trigger: 'blur' },
          { pattern: /^\S{1,10}$/, message: '用户昵称必须是1-10位的非空字符', trigger: 'blur' }
        ],
        email: [{ required: true, message: '用户邮箱是必填项', trigger: 'blur' }]
      }
    }
  }
}
</script>

<style></style>
